package com.hanwei.uap.common.exception;

import com.alibaba.fastjson.JSONObject;

import java.text.MessageFormat;

/**
 * @Author:zhaoam
 * @Description:异常基类，所有系统和业务异常都必须继承于此异常
 * @Date: 2017/9/14 14:38.
 * 错误编码规则：2位模块编号+4位错误编号
 * 000000表示成功
 * 1X:系统类错误码
 * 10 通信类错误 系统通信产生的错误类 11 文件类错误 12 数据库类错误 13中间件类错误MQ等
 * 2X:报文类错误码
 * 20 报文格式类错误
 * 3X-9X:业务模块错误码
 */
public class AppException extends RuntimeException {
    protected String code;
    protected String desc;

    public AppException() {
        super();
    }

    public AppException(String code, String format, Object... args) {
        super(code);
        this.code = code;
        this.desc = MessageFormat.format(format, args);
    }

    public AppException(String code, String format) {
        super(code);
        this.code = code;
        this.desc = format;
    }

    public AppException(String code, Throwable t, String format, Object... args) {
        super(t);
        this.code = code;
        this.desc = MessageFormat.format(format, args);
    }

    public AppException(String code, Throwable t, String format) {
        super(t);
        this.code = code;
        this.desc = format;
    }

    public AppException(String message, Throwable cause) {
        super(message, cause);
    }

    public AppException(Throwable cause) {
        super(cause);
    }

    public AppException(String message) {
        super(message);
    }

    public static String getLocation(StackTraceElement[] stack) {
        return stack[0].getClassName() + '.' + stack[0].getMethodName() + ':' + stack[0].getLineNumber();
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getLocation() {
        return getLocation(getStackTrace());
    }

    public String toJson() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        jsonObject.put("desc", desc);
        if (null != getCause())
            jsonObject.put("exception", getCause().toString());
        return jsonObject.toJSONString();
    }

    @Override
    public String toString() {
        return "AppException{" +
                "code='" + code + '\'' +
                ", desc='" + desc + '\'' +
                '}';
    }
}
